package moe.oil.db.api;

import lombok.Setter;
import moe.oil.db.entity.Comments;
import moe.oil.db.service.CommentsService;
import moe.oil.dto.school.CommentsDTO;
import moe.oil.exception.comments.CommentsIdNullException;
import moe.oil.validation.grop.OnUpdate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * author: 紫月
 * Date: 2022/04/19 16:58
 * Description:
 *
 * @author - -
 */
@RestController
@RequestMapping("/comments")
@Setter(onMethod_ = @Autowired)
public class CommentsController {

    private CommentsService commentsService;

    // 根据Id查询评论
    @GetMapping("/{id}")
    public CommentsDTO findByIdComments(@PathVariable("id") Long id) {
        return commentsService.selectCommentsId(id).orElseThrow(() -> new CommentsIdNullException(id));
    }

    // 查询全部评论
    @GetMapping("/{page}/{size}")
    public List<CommentsDTO> findAllComments(@PathVariable("page") int page, @PathVariable("size") int size) {
        return commentsService.selectCommentsAll(PageRequest.of(page, size));
    }

    // 添加评论 根据id 插入 school 查询是否做到全部数据显示
    @PostMapping
    public CommentsDTO saveComments(@Validated(OnUpdate.class) @RequestBody CommentsDTO commentsDto) {
        return commentsService.saveComments(commentsDto).get();
    }

    // 根据ID删除评论
    @DeleteMapping("/{id}")
    public int deleteByIdComments(@PathVariable("id") Long id) {
        return commentsService.deleteCommentsId(id);
    }

    // 修改
    @PutMapping
    public CommentsDTO updateComments(@Validated CommentsDTO commentsDto) {
        return commentsService.updateComments(new Comments(commentsDto)).get();
    }

}
